package com.mywork.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.bean.WorkMeetingListBean;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.SelMeetingSignInReq;
import com.ciko.code.utils.NetWorkUtils;
import com.mywork.R;
import com.ui.dialog.CustomDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 会议签到(定位签到)
 */
public class WorkMeetingDetailSignActivity extends BaseActicity implements HttpResponseListener {
    /**
     * 签到时间
     */
    private TextView tv_work_sign_data_time;
    /**
     * 签到地址
     */
    private TextView tv_work_sign_address;
    /**
     * 确定
     */
    private Button tv_work_sign_ok;
    /**
     * 对话框
     */
    private ProgressDialog progressDialog;
    public final static int SIGN_CODE = 123;

    private static AMapLocationClient mLocationClient = null;

    //    private static String actualAddr;//地址
    private static Double actualLat;//经度
    private static Double actualLon;//纬度
    private WorkMeetingListBean bean;

    @Override
    protected void initTopBar() {
        setTitle("会议签到");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_workmeeting_detail_sign);
    }

    @Override
    protected void initView() {
        tv_work_sign_data_time = findViewByID(R.id.tv_work_sign_data_time);
        tv_work_sign_address = findViewByID(R.id.tv_work_sign_address);
        tv_work_sign_ok = findViewByID(R.id.tv_work_sign_ok);
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
        bean = (WorkMeetingListBean) getIntent().getSerializableExtra("WorkMeetingListBean");
        //签到时间
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);
        String dataTime = "签到时间: " + format.format(date);
        tv_work_sign_data_time.setText(dataTime);

        mLocationClient = new AMapLocationClient(getApplicationContext());
        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        AMapLocationListener mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(final AMapLocation aMapLocation) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    tv_work_sign_address.setText(aMapLocation.getAddress());
//                    actualAddr = aMapLocation.getAddress();
                    actualLat = aMapLocation.getLatitude();
                    actualLon = aMapLocation.getLongitude();
                    mLocationClient.stopLocation();
                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
        mLocationClient.startLocation();
    }

    @Override
    protected void initListener() {
        tv_work_sign_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//跳转到地图界面
                toLocationActivity();
            }
        });
        tv_work_sign_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {//签到
                if (!NetWorkUtils.isConnected(WorkMeetingDetailSignActivity.this)) {
                    showMsgDialog("网络错误，请检查网络!",false);
                    return;
                }
                progressDialog = ProgressDialog.show(WorkMeetingDetailSignActivity.this, "", "正在签到...");
                try {
                    //测量距离是否在范围内
                    LatLng start = new LatLng(Double.parseDouble(bean.getLat()), Double.parseDouble(bean.getLon()));//会议坐标
                    LatLng end = new LatLng(actualLat, actualLon);//定位坐标
                    if (AMapUtils.calculateLineDistance(start, end) < Double.parseDouble(bean.getDistance())) {
                        doRequestHttp(new SelMeetingSignInReq(String.valueOf(bean.getMeetingId())));
                    } else {
                        showMsgDialog1("当前位置不在会议签到地址区域内!");
                    }
                } catch (NumberFormatException e) {
                    showMsgDialog("数据转换失败",false);
                } catch (NullPointerException e) {
                    showMsgDialog("数据为空",false);
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        super.onResponseSuccess(response, tag);
        showMsgDialog("签到成功",true);
    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        super.onResponseFail(tag, resultCode);
        switch (resultCode) {
            case 1011:
                showMsgDialog("未查询到该次会议相关信息",false);
                break;
            case 4001:
                showMsgDialog("已签到",true);
                break;
            case 4002:
                showMsgDialog("非该次会议与会者签到",false);
                break;
            case 4003:
                showMsgDialog("请在正确的时间内签到",false);
                break;
            case 9997:
                showMsgDialog("必填参数缺失",false);
                break;
            default:
                showMsgDialog("签到失败",false);
                break;
        }
    }

    private void showMsgDialog(String message,final boolean type) {
        progressDialog.dismiss();
        new CustomDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (type) {
                            setResult(SIGN_CODE);
                            finish();
                        }
                    }
                }).create().show();
    }

    private void showMsgDialog1(String message) {
        progressDialog.dismiss();
        new CustomDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("重新定位", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        toLocationActivity();
                    }
                }).create().show();
    }

    /**
     * 跳转到地图界面
     */
    private void toLocationActivity() {
        Intent intent = new Intent(WorkMeetingDetailSignActivity.this, WorkMeetingSignLocationActivity.class);
        startActivity(intent);
    }
}
